package com.apes.framework.plugin.condition;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 功能：
 *
 * @author xul
 * @create 2018-12-08 16:37
 */
public class Bucket {
    private final Date start;
    private final Date end;

    public Bucket(Date start, Date end) {
        if (start.after(end)) {
            throw new IllegalArgumentException("时间段无效(开始日期需要小于结束日期)");
        }
        this.start = start;
        this.end = end;
    }

    public Bucket(long startTime, long endTime) {
        this(new Date(startTime), new Date(endTime));
    }

    public static Bucket union(List<Bucket> buckets) {
        if (buckets == null || buckets.size() <= 1) {
            return null;
        }
        sort(buckets);
        for (int i = 0; i < buckets.size() - 1; i++) {
            long start = buckets.get(i).getStartTime();
            long end = buckets.get(i).getEndTime();
            for (int j = i + 1; j < buckets.size(); j++) {
                if (buckets.get(j).getStartTime() > buckets.get(i).getStartTime()) {
                    start = buckets.get(j).getStartTime();
                } else if (buckets.get(i).getStartTime() > buckets.get(j).getStartTime()) {
                    start = buckets.get(i).getStartTime();
                }
                if (buckets.get(j).getEndTime() < buckets.get(i).getEndTime()) {
                    end = buckets.get(j).getEndTime();
                } else if (buckets.get(i).getEndTime() < buckets.get(j).getEndTime()) {
                    end = buckets.get(i).getEndTime();
                }
                if (start <= end) {
                    return new Bucket(start, end);
                }
            }
        }
        return null;
    }

    private static void sort(List<Bucket> buckets) {
        Collections.sort(buckets, new Comparator<Bucket>() {
            @Override
            public int compare(Bucket o1, Bucket o2) {
                if (o1.getEnd().compareTo(o2.getEnd()) > 0) {
                    return 1;
                }
                if (o1.getEnd().compareTo(o2.getEnd()) == 0) {
                    return 0;
                }
                return -1;
            }
        });
    }


    public Date getStart() {
        return start;
    }

    public Date getEnd() {
        return end;
    }

    public long getStartTime() {
        return start.getTime();
    }

    public long getEndTime() {
        return end.getTime();
    }
}
